import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test01/config/config.dart';
import 'package:test01/model/user_model.dart';

import 'crop_image_route.dart';

class MyContent extends StatefulWidget {
  const MyContent({Key? key}) : super(key: key);

  @override
  _MyContentState createState() => _MyContentState();
}

class _MyContentState extends State<MyContent> {
  final ImagePicker _picker = ImagePicker();

  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  int selectIndex = 0;
  int userId = 0;
  var endTime = new DateTime.now();
  Image? resImage;
  final _picture =
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.pintu360.com%2Fdefault%2Fzz_avatar_default.png&refer=http%3A%2F%2Fimg.pintu360.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637423721&t=16c7870162f33a2e6956aed97892068f";
  UserModelItem _user = new UserModelItem();

  _getUserInfo(int userId) async {
    var api = "${Config.domain}user/getUserById?userId=$userId";
    var result = await Dio().get(api);
    var userModel = UserModel.fromJson(result.data!);
    if (userModel.status == 200) {
      setState(() {
        _user = userModel.data!;
        _getAvatar();
      });
    }
  }

  _changeColor(int index) {
    setState(() {
      selectIndex = index;
    });
    Future.delayed(const Duration(milliseconds: 200), () {
      setState(() {
        selectIndex = 0;
      });
    });
  }

  _getImage() async {
    // final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
    photo!.readAsBytes().then((value) {
      cropImage(value);
    });
  }

  void cropImage(Uint8List image) async {
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;
    await Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => CropImageRoute(
                  arguments: image,
                ))).then((value) {
      setState(() {
        _uploadAvatar(value!);
      });
    });
  }

  _getAvatar() async {
    var api = "${Config.domain}user/getAvatar?userId=${_user.userId}";
    var result = await Dio().post(api);
    List<dynamic> listData = result.data["data"];
    List<int> listInt = List.from(listData.map((e) => int.parse(e)));
    Uint8List uint8list = Uint8List.fromList(listInt);
    setState(() {
      resImage = Image.memory(uint8list, width: 120.w, height: 120.w, fit: BoxFit.fill,);
    });
  }

  void _uploadAvatar(Uint8List file) async {
    ///上传头像
    var api = "${Config.domain}user/uploadAvatar";
    var result = await Dio().post(api, data: {
      "file": file,
      "userId": _user.userId,
      "nickName": _user.nickName
    });
    List<dynamic> listData = result.data["data"];
    List<int> listInt = List.from(listData.map((e) => int.parse(e)));
    Uint8List uint8list = Uint8List.fromList(listInt);
    setState(() {
      resImage = Image.memory(uint8list, width: 120.w, height: 120.w, fit: BoxFit.fill,);
    });
  }

  void _backLogin() {
    _prefs.then((value) {
      if(value.getInt("userId") != null) {
        value.remove("userId");
        Navigator.pushNamed(context, "/login");
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _prefs.then((value) {
      if (value.getInt("userId") != null) {
        userId = value.getInt("userId")!;
        _getUserInfo(userId);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        buildTitle(),
        SizedBox(
          height: 20.h,
        ),
        buildWidgetList(Icons.settings, 1, "修改密码", () {
          _changeColor(1);
          Navigator.pushNamed(context, "/changeInfo");
        }),
        buildWidgetList(Icons.favorite_border_outlined, 2, "我的收藏", () {
          _changeColor(2);
        }),
        buildWidgetList(Icons.close, 3, "退出登录", () {
          _changeColor(3);
          _backLogin();
        }),
      ],
    );
  }

  Widget buildWidgetList(
      IconData iconData, int index, String title, Function() callBack) {
    Color _color = Colors.white;
    Color _selectColor = Colors.grey;
    return Container(
      alignment: Alignment.center,
      color: selectIndex == index ? _selectColor : _color,
      padding: EdgeInsets.only(left: 20.w),
      height: 100.h,
      width: double.infinity,
      child: Column(
        children: [
          GestureDetector(
            onTap: callBack,
            child: Container(
              height: 98.h,
              width: double.infinity,
              alignment: Alignment.center,
              child: Row(
                children: [
                  Icon(
                    iconData,
                    size: 40.w,
                  ),
                  SizedBox(width: 20.w),
                  Text(
                    title,
                    style: TextStyle(fontSize: 28.w, color: Colors.black87),
                  )
                ],
              ),
            ),
          ),
          Divider(
            height: 2.h,
            indent: 70.w,
            color: Colors.black26,
          )
        ],
      ),
    );
  }

  Widget buildTitle() {
    if (_user.userId != null) {
      return Container(
        height: 300.h,
        color: Colors.white,
        margin: EdgeInsets.only(top: 15.w),
        padding: EdgeInsets.only(left: 40.w),
        child: Row(
          children: [
            GestureDetector(
                onTap: () {
                  _getImage();
                },
                child: Container(
                    width: 120.w,
                    height: 120.w,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(20.w),
                        child: resImage ??
                            Image.network(
                              _picture,
                              fit: BoxFit.fill,
                            )))),
            Container(
              padding: EdgeInsets.only(left: 20.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    _user.nickName!,
                    style: TextStyle(fontSize: 33.w, color: Colors.black87),
                  ),
                  Text(
                      "云旅${endTime.difference(DateTime.parse(_user.createTime!)).inDays}天",
                      style: TextStyle(fontSize: 23.w, color: Colors.black45))
                ],
              ),
            )
          ],
        ),
      );
    } else {
      return const Text("");
    }
  }
}
